<script setup>

import CardBox from "@/components/CardBox/index.vue";
import {useRouter} from "vue-router";
import {Download} from "@element-plus/icons-vue";
import {
  addAchievementApi,
  deleteAcademicOutputApi,
  detailsAcademicOutputApi,
  downWallAcademicOutputApi,
  downWallActualOutPutApi, exportAchievements1Api,
  getAchievementListApi,
  getAllAchievementTypeApi, getChildTypeListApi, getNoMeStudentListApi,
  getStudentListApi, getTeacherListApi,
  updateAcademicOutputApi,
  wallAcademicOutputApi,
  wallActualOutPutApi
} from "@/api/school.js";
import useUserStore from "@/store/modules/user.js";
import ImageUpload from "@/components/ImageUpload/index.vue";

const {proxy} = getCurrentInstance();

const router = useRouter()
const userStore = useUserStore()
const state = reactive({
  studentList: [],
  permission: [],
  formRules: {
    stuId: [
      {required: true, message: '请选择学生', trigger: 'change'},
    ],
    acTitle: [
      {required: true, message: '请输入作品（团队）名称', trigger: 'blur'},
    ],
    resultTypeId: [
      {required: true, message: '请选择成果类型', trigger: 'change'},
    ],
    awardLevel: [
      {required: true, message: '请输入获奖等级', trigger: 'blur'},
    ],
    teacherIds: [
      {required: true, message: '请选择指导老师', trigger: 'change'},
    ],
  },
  editForm: {
    id: '',
    stuId: '',
    acTitle: '',
    acFile: '',
  },
  achievementTypeList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    teacherType: 0,
    memberId: '',
  },
  total: 0,
  title: '新增学术成果',
  ids: [],
})
const showDia1 = ref(false)

const multipleSelection = ref([])

const selectable = (row) => ![].includes(row.id)
const handleAdd = async () => {
  const res = await getStudentListApi()
  if (res.code == 200) {
    state.studentList = res.data
  }
  showDia1.value = true
}

const handleEdit = async (id) => {
  await getAllAchievementType()
  // 获取详情
  const res = await detailsAcademicOutputApi({id})
  if (res.code == 200) {
    await getChildType(res.data.resultTypeId)
    state.editForm = {
      ...state.editForm,
      ...res.data
    }
    const data = {
      ids: res.data.memberIds
    }
    const res2 = await getNoMeStudentListApi(data)
    state.studentList = res2.data
    showDia1.value = true
    state.title = '编辑'
  }
}

const searchStudent = async (query) => {
  const res = await getStudentListApi({stuName: query})
  if (res.code == 200) {
    state.studentList = res.data
  }
}

const submitForm = () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      let res = ''
      if (state.editForm.id == '') {
        res = await addAchievementApi(state.editForm)
      } else {
        res = await updateAcademicOutputApi(state.editForm)
      }

      if (res.code == 200) {
        proxy.$message.success('操作成功')
        handleClose()
        await getDataList()
      }
    }
  })
}

const getAllAchievementType = async () => {
  const res = await getAllAchievementTypeApi()
  if (res.code == 200) {
    state.achievementTypeList = res.data
  }
}

const getDataList = async () => {
  if (state.permission.includes('superManager') || state.permission.includes('admin')) {
    delete state.queryParams.teacherType
  }
  const res = await getAchievementListApi(state.queryParams)
  if (res.code == 200) {
    state.tableData = res.rows
    state.total = res.total
  }
}

const handleDelete = (id) => {
  proxy.$modal.confirm('是否删除该数据？').then(async () => {
    const res = await deleteAcademicOutputApi({id})
    if (res.code == 200) {
      proxy.$modal.msgSuccess("删除成功")
    }
    await getDataList()
  })
}

const handleClose = () => {
  showDia1.value = false
  state.editForm = {
    id: '',
    stuId: '',
    acTitle: '',
  }
  proxy.resetForm("formRef");
  state.title = '新增学术成果'
}

const resetSearch = () => {
  proxy.resetForm("queryRef");
  state.queryParams = {
    pageNum: 1,
    pageSize: 10,
  }
  getPermission()
  getDataList()
}

const handleChecked = (id, checked) => {
  const index = state.ids.findIndex(item => item.id === id)
  if (index !== -1) {
    state.ids.splice(index, 1)
  } else {
    state.ids.push(id)
  }
}

const handleWall = () => {
  if (state.ids.length == 0) {
    proxy.$modal.msgError("请选择要操作的数据")
  } else {
    proxy.$modal.confirm('是否上墙该数据？').then(async () => {
      const res = await wallAcademicOutputApi({ids: state.ids})
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
        await getDataList()
      }
    })
  }
}

const handleDownWall = () => {
  if (state.ids.length == 0) {
    proxy.$modal.msgError("请选择要操作的数据")
  } else {
    proxy.$modal.confirm('是否下墙该数据？').then(async () => {
      const res = await downWallAcademicOutputApi({ids: state.ids})
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
        await getDataList()
      }
    })
  }
}

const handleApproval = () => {
  router.push("/approvalManagement/teacherApproval")
}

const changeStu = async (id) => {
  state.editForm.instructorTeacherId = ''
  // 获取教师列表
  const res = await getTeacherListApi({id})
  if (res.code == 200) {
    state.teacherList = res.data
  }
}

// 参与人员
const handleJoin = (outPutId) => {
  router.push({
    path: "stuResultDisplayJoin",
    query: {
      outPutId
    }
  })
}

const getIsStudent = () => {
  return userStore.roles.includes('student')
}

// 成果导出
const handleExport = async (item) => {
  proxy.download("/school/academicOutput/export-word", {
    id: item.id
  }, `${item.stuName}获奖情况.docx`);
}

// 获取当前老师的权限信息
const getPermission = async () => {
  state.permission = userStore.roles
  if (state.permission.includes('teacher')) {
    state.teacherType = 0
  } else if(state.permission.includes('teacher2')){
    state.teacherType = 1
  }else if(state.permission.includes('duizhang')){
    state.teacherType = 3
  }else if (state.permission.includes('superManager')){
    state.teacherType = 2
  }
  state.queryParams.teacherType = state.teacherType
}


const remoteMethod = async (val) => {
  state.loadding = true
  const data = {
    stuName: val
  }
  const res = await getNoMeStudentListApi(data)
  state.loadding = false
  state.studentList = res.data
}

const handleExport2 = () => {
  proxy.download("school/academicOutput/export-word2", {
    ids: state.ids,
  }, `学科竞赛批量导出${new Date().getTime()}.docx`);
}

// 获取子类型
const getChildType = async (id) => {
  state.editForm.resultTypeId2 = ''
  const data = {
    pageNum: 1,
    pageSize: 9999,
    resLevelId: id
  }
  const res = await getChildTypeListApi(data)
  if (res.code == 200 && res.total > 0) {
    state.childTypeList = res.rows
  }
  // 显示等级、类别
  const obj = state.achievementTypeList.find(item => item.id == id)
  console.log(obj, "obj")
  state.editForm.show1 = obj.resType
  state.editForm.show2 = obj.hightLevel == 1 ? '是' : '否'
  state.editForm.show3 = obj.resLevel
}

const handleSelectionChange = (val) => {
  state.ids = val.map(item => item.id)
}


onMounted(() => {
  getAllAchievementType()
  getPermission()
  getDataList()

})
</script>

<template>
  <div class="outBox">
    <CardBox style="margin-bottom: 20px" title="筛选查询">
      <template #btn-cont>
        <el-button type="primary" @click="getDataList">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </template>
      <template #content>
        <el-form :model="state.queryParams" label-width="80" inline="true" ref="queryRef">
          <el-form-item label="竞赛名称">
            <el-select v-model="state.queryParams.resultTypeId" placeholder="请选择" style="width: 200px;">
              <el-option v-for="item in state.achievementTypeList" :key="item.id" :label="item.resName"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="获奖等级">
            <el-input v-model="state.queryParams.awardLevel" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="团队成员">
            <el-select
                v-model="state.queryParams.memberId"
                placeholder="请选择"
                style="width: 240px"
                filterable
                remote
                :remote-method="remoteMethod"
                :loading="state.loadding"
            >
              <el-option
                  v-for="item in state.studentList"
                  :key="item.id"
                  :label="item.stuName + '-' + item.stuNum"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="审核结果">
            <el-select v-model="state.queryParams.acAudit" placeholder="请选择" style="width: 200px;">
              <el-option label="待审核" value="1"/>
              <el-option label="通过" value="2"/>
              <el-option label="拒绝" value="3"/>
            </el-select>
          </el-form-item>
          <el-form-item label="是否上墙">
            <el-select v-model="state.queryParams.acWall" placeholder="请选择" style="width: 200px;">
              <el-option label="是" value="2"/>
              <el-option label="否" value="1"/>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </CardBox>
    <CardBox title="数据列表">
      <template #btn-cont v-if="!getIsStudent()">
        <el-select v-model="state.queryParams.teacherType" placeholder="请选择" @change="getDataList"
                   v-if="!state.permission.includes('superManager') && !state.permission.includes('admin')"
                   style="width: 150px;margin-right: 15px">
          <el-option label="学业导师" :value="0" v-if="state.permission.includes('teacher')"/>
          <el-option label="专业教师" :value="1" v-if="state.permission.includes('teacher2')"/>
          <el-option label="中队长" :value="3" v-if="state.permission.includes('duizhang')"/>
        </el-select>
        <el-button type="primary" @click="handleExport2">导出</el-button>
        <!--          <el-button type="primary" @click="handleDownWall">下墙</el-button>-->
        <!--        <el-button type="primary" @click="handleApproval">成果审核</el-button>-->
        <!--        <el-button type="primary" @click="handleAdd">上传成果</el-button>-->
      </template>
      <template #content>
        <el-table :data="state.tableData" style="width: 100%"    @selection-change="handleSelectionChange"  row-key="id">
          <el-table-column type="selection" :selectable="selectable" width="55">
<!--            <template #default="scope">-->
<!--              <el-checkbox v-model="scope.row.checked" @change="handleChecked(scope.row.id, scope.row.checked)"/>-->
<!--            </template>-->
          </el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center"/>
          <el-table-column prop="recognitionName" label="竞赛名称" align="center"/>
          <el-table-column prop="recognitionLevel" label="竞赛等级" align="center"/>
          <el-table-column prop="awardLevel" label="获奖等级" align="center"/>
          <el-table-column prop="participants" label="团队成员" align="center">
            <template #default="scope">
              <span style="margin-right: 5px" v-for="(item,index) in scope.row.participants">{{ item.stuName }} <span
                  v-if="index != scope.row.participants.length - 1">、</span></span>
            </template>
          </el-table-column>
          <el-table-column prop="acTime" label="竞赛类别" align="center">
            <template #default="scope">
              {{ state.achievementTypeList.find(item => item.id == scope.row.resultTypeId).resName }}
            </template>
          </el-table-column>
          <el-table-column prop="acTime" label="是否系部专业赛" align="center">
            <template #default="scope">
              <el-tag>
                {{
                  state.achievementTypeList.find(item => item.id == scope.row.resultTypeId).hightLevel == 1 ? '是' : '否'
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="teachers" label="指导老师" align="center">
            <template #default="scope">
              <el-tag style="margin-right: 5px" v-for="item in scope.row.teachers">{{ item.teacherName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" link @click="handleEdit(scope.row.id)">成果详情</el-button>
              <el-button type="primary" size="small" link @click="handleExport(scope.row)">导出</el-button>
              <!--              <el-button type="primary" size="small" link @click="handleJoin(scope.row.id)">成员详情</el-button>-->
              <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)" v-if="state.queryParams.teacherType !== 3">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pageBox">
          <pagination
              v-show="state.total > 0"
              :total="state.total"
              v-model:page="state.queryParams.pageNum"
              v-model:limit="state.queryParams.pageSize"
              @pagination="getDataList()"
          />
        </div>
      </template>
    </CardBox>

    <el-dialog :title="state.title" v-model="showDia1" width="800" center>
      <div>
        <el-form label-width="140px" :model="state.editForm" :rules="state.formRules" ref="formRef">
          <el-col :span="24">
            <el-row>
              <el-form-item label="竞赛名称" prop="resultTypeId">
                <el-select v-model="state.editForm.resultTypeId" placeholder="请选择" style="width: 200px;"
                           @change="getChildType">
                  <el-option v-for="item in state.achievementTypeList" :key="item.id" :label="item.resName"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="子赛事名称" prop="resultTypeId2" v-if="state.childTypeList.length > 0">
                <el-select v-model="state.editForm.resultTypeId2" placeholder="请选择" style="width: 200px;"
                           @change="changeChild">
                  <el-option v-for="item in state.childTypeList" :key="item.id" :label="item.resName"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-row>
              <el-form-item label="竞赛类型">
                <span style="min-width: 200px">{{ state.editForm.show1 || '' }}</span>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="是否系部认可专业赛">
                {{ state.editForm.show2 || '' }}
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="赛事认定等级">
                {{ state.editForm.show3 || '' }}
              </el-form-item>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-form-item label="获奖等级" prop="awardLevel">
              <el-input v-model="state.editForm.awardLevel"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="第一作者">-->
          <!--              {{ userStore.nickName }}-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="团队成员" prop="memberIds">
              <el-select
                  v-model="state.editForm.memberIds"
                  multiple
                  placeholder="请选择"
                  style="width: 240px"
                  :multiple-limit="5"
                  filterable
                  remote
                  :remote-method="remoteMethod"
                  :loading="state.loadding"
              >
                <el-option
                    v-for="item in state.studentList"
                    :key="item.id"
                    :label="item.stuName + '-' + item.stuNum"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="指导教师" prop="teacherIds">
              <el-select
                  v-model="state.editForm.teacherIds"
                  multiple
                  placeholder="请选择"
                  style="width: 240px"
                  :multiple-limit="3"
              >
                <el-option
                    v-for="item in state.teacherList"
                    :key="item.id"
                    :label="item.teacherName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
        <el-form label-width="150" :model="state.editForm" label-position="top" :rules="state.formRules">
          <el-form-item label="上传获奖证书的图片资料" label-position="top" label-width="150" prop="acFile">
            <div class="uploadBox">
              <ImageUpload
                  :multiple="false"
                  :limit="1"
                  v-model="state.editForm.acFile"
              />
            </div>
          </el-form-item>
        </el-form>
        <div class="footer">
          <el-button @click="handleClose">返回</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.uploadBox {
  margin-left: 50px;
}

.footer {
  text-align: center;
}

.btns {
  display: flex;
}
</style>
